package com.qf.java2102.qihaonan.hotel.controller.front;

import com.qf.java2102.qihaonan.hotel.entity.ResultVO;
import com.qf.java2102.qihaonan.hotel.pojo.User;
import com.qf.java2102.qihaonan.hotel.service.IUserService;
import com.qf.java2102.qihaonan.hotel.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author qhn
 * @version 1.0
 */
@WebServlet("/user/login")
public class UserController extends HttpServlet {

    private IUserService userService = new UserServiceImpl();

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String inputVcode=request.getParameter("inputVcode");
        //校验验证码
        String code= (String) request.getSession().getAttribute("code");
        //校验码非空判断
        if (!inputVcode.isEmpty()&&inputVcode.equalsIgnoreCase(code)) {
            HttpSession session = request.getSession();
            ResultVO<User> resultVO = userService.login(username, password);
            if (resultVO.getSuccess()) {
                if (resultVO.getData().getIsAdmin().intValue() == 0) {
                    //不是管理员，去前台
                    session.setAttribute("frontUser", resultVO.getData());
                    response.sendRedirect(request.getContextPath() + "/front/index.jsp");
                } else {
                    //去后台
                    session.setAttribute("adminUser", resultVO.getData());
                    response.sendRedirect(request.getContextPath() + "/backend/index.jsp");
                }
            } else {
                response.sendRedirect(request.getContextPath() + "/login.jsp");
            }
        }else {
            response.sendRedirect(request.getContextPath() + "/login.jsp");
        }

    }

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
